//
//  LXContactsViewController.m
//  bgms_d
//
//  Created by lachesis-zhu on 09/08/2017.
//  Copyright © 2017 lachesis-zhu. All rights reserved.
//

#import "LXContactsViewController.h"
#import "BleSearchViewController.h"

@interface LXContactsViewController () <LXActionSheetDelegate, BLETransDeviceSingletonDelegate, BleSearchViewControllerDelegate>
{
    BLETransDeviceSingleton *ble;
    NSTimer *timer;
    NSTimer *connectTimer;
    NSInteger connectDev;
}

@end

@implementation LXContactsViewController

#pragma mark -  public method
- (void)connectSuccessView {
    self.warnLabel.text = @"Your speakers are now linked!";
    self.nameLabel.text = @"";
    self.pairBtn.hidden = YES;
    self.linkBtn.hidden = NO;
    self.cuowuImage.hidden = YES;
    self.roundIcon.hidden = YES;
    self.devIconImage1.hidden = NO;
    self.devIconImage2.hidden = NO;
    self.boardView.hidden = NO;
    self.connectImage.hidden = NO;
    [self.linkBtn setTitle:@"Unlink" forState:UIControlStateNormal];
}

- (void)connectFailView {
    self.warnLabel.text = @"Could not find second speaker to pair";
    self.nameLabel.text = @"";
    self.pairBtn.hidden = YES;
    self.roundIcon.hidden = NO;
    self.linkBtn.hidden = YES;
    self.cuowuImage.hidden = NO;
    self.devIconImage1.hidden = YES;
    self.devIconImage2.hidden = YES;
    self.boardView.hidden = NO;
    self.connectImage.hidden = YES;
    [self.linkBtn setTitle:@"Link" forState:UIControlStateNormal];
}

- (void)connectReadyView {
    self.warnLabel.text = @"press another xpetidion 850 “link” button to link";
    self.nameLabel.text = @"Not Connected";
    self.warnLabel.hidden = NO;
    self.pairBtn.hidden = NO;
    self.roundIcon.hidden = YES;
    self.linkBtn.hidden = YES;
    self.cuowuImage.hidden = YES;
    self.devIconImage1.hidden = YES;
    self.devIconImage2.hidden = YES;
    self.boardView.hidden = YES;
    self.connectImage.hidden = YES;
    [self.linkBtn setTitle:@"Unlink" forState:UIControlStateNormal];
}
#pragma mark -  life cycle
- (void)dealloc
{
    
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.firstLink = NO;
    self.warnLabel.numberOfLines = 2;
    self.warnLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    ble = [BLETransDeviceSingleton sharedInstance];
    ble.delegate = self;
    
    self.linkBtn.layer.borderColor = kAppNormalTextColor.CGColor;
    self.linkBtn.layer.borderWidth = 1;
    
    timer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    
    [self addNotification];
}

- (void)viewDidAppear:(BOOL)animated
{
    self.linkBtn.layer.cornerRadius = self.linkBtn.frame.size.height / 2;
    self.linkBtn.layer.masksToBounds = YES;
}

- (void)timerRun
{
    [self refetchTws];
}

- (void)connectRun
{
    [connectTimer invalidate];
    connectTimer = nil;
    [EasyLoadingView hidenLoading];
    self.linkFail = YES;
    [self connectReadyView];
}


- (IBAction)connectNext:(id)sender {
    if (!timer) {
        timer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    }
    if (!connectTimer) {
        connectTimer = [NSTimer timerWithTimeInterval:12.0 target:self selector:@selector(connectRun) userInfo:nil repeats:NO];
        [[NSRunLoop currentRunLoop] addTimer:connectTimer forMode:NSDefaultRunLoopMode];
    }
    [EasyLoadingView showLoadingText:@"Connecting..."];
    [ble connectSubDevice];
}

- (IBAction)unlink:(id)sender {
//    if (self.linkFail) {
//        if (!timer) {
//            timer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
//            [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
//        }
//        [EasyLoadingView showLoadingText:@"Connecting..."];
//        [ble connectRootDevice];
//    } else {
//        [timer invalidate];
//        timer = nil;
        [self requirePair:NO];
        [self connectReadyView];
//        [self performSelector:@selector(connectRootDevDelay) withObject:nil afterDelay:1];
//    }
}

- (void)connectRootDevDelay {
    [ble connectRootDevice];
}
#pragma mark -  notification
- (void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(twsNotication:) name:COMMON_CHARACTERISTIC_UUID object:nil];
}

-(void)twsNotication:(NSNotification *)notification
{
    NSData *data = notification.userInfo[kAppHeadUnitData];
    Byte *MessageBt = (Byte *)[data bytes];
    NSInteger type = MessageBt[0];
    if (type == 6) {
        NSInteger tws = MessageBt[2];
        NSLog(@"the tws is %ld", (long)tws);
        switch (tws) {
            case 0:
                [connectTimer invalidate];
                connectTimer = nil;
                [self connectReadyView];
                self.linkFail = YES;
                break;
                
            case 1:
                [self connectReadyView];
                break;
                
            case 2:
                [self connectSuccessView];
                if (connectTimer != nil) {
                    [connectTimer invalidate];
                    connectTimer = nil;
                }
                [EasyLoadingView hidenLoading];
                self.linkFail = NO;
                break;
                
            default:
                break;
        }
    }
}

- (void)refetchTws {
    UInt8 data[3];
    data[0] = 0x06;
    data[1] = 0x01;
    data[2] = 0x00;
    [[BLETransDeviceSingleton sharedInstance] characteristc:COMMON_CHARACTERISTIC_UUID sendHostCmd:data lenght:3];
}

- (void)requirePair:(BOOL)link {
    UInt8 data[3];
    data[0] = 0x06;
    data[1] = link ? 0x03 : 0x04;
    data[2] = 0x00;
    [[BLETransDeviceSingleton sharedInstance] characteristc:COMMON_CHARACTERISTIC_UUID sendHostCmd:data lenght:3];
}


- (void)BLETransDeviceSingletonConnected:(BOOL)connected
{
    if (connected) {
        [self performSelector:@selector(delayMethod) withObject:nil afterDelay:1];
    } else {
        [self connectReadyView];
        self.linkFail = YES;
    }
}

- (void)delayMethod {
    [self requirePair:YES];
}

- (void)searchViewController:(BleSearchViewController *)vc backData:(NSString *)data
{
    if ([data isEqualToString:@"success"]) {
        self.nameLabel.text = @"Linked success";
        self.warnLabel.hidden = YES;
    }
}
#pragma mark -  memoryWarning

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
